package com.gupt.youhd.common;/*
@author name
@data 2023/4/23-22:41
*/
import com.gupt.youhd.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理
 */
@Slf4j
//最终返回json数据
@ResponseBody
//捕获(拦截哪些类抛出的异常  annotations(注解
@ControllerAdvice(annotations = {RestController.class, Controller.class})

public class GlobalExceptionHandler {

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException exception){
        log.info("捕获异常为：{}",exception.getMessage());

        String message = exception.getMessage();
        if(message.contains("Duplicate entry")){
            String[] msg = message.split(" "); //切割字符串变成数组
            String error = msg[2] + " 已存在";
            return R.error(error);
        }
        return R.error("系统错误，请重试");
    }

    @ExceptionHandler(BusinessException.class)
    public R<String> exceptionHandler(BusinessException exception){
        log.info("捕获异常为:{}",exception.getMessage());

        return R.error(exception.getMessage());
    }


    @ExceptionHandler(Exception.class)
    public R handler(Exception e){
        e.printStackTrace();
        return R.error("系统异常");
    }
}
